package com.training.java.redbox;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.training.java.redbox.service.CustomerService;

public class SignupAction extends DispatchAction {

	public ActionForward redirect(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		return mapping.findForward("signup");
	}

	public ActionForward submit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		CustomerForm customerForm = (CustomerForm) form;

		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
		CustomerService service = context.getBean(CustomerService.class);
		
		boolean customerExists = service.checkCustomerExistence(customerForm
				.getUserName());

		if (!customerExists) {

			service.addCustomer(0, customerForm.getFirstName(),
					customerForm.getLastName(), customerForm.getAddress(),
					customerForm.getCity(), customerForm.getState(),
					customerForm.getZipCode(), customerForm.getUserName(),
					customerForm.getPassword());

			return mapping.findForward("login");

		} else {

			ActionErrors errors = new ActionErrors();
			errors.add("username.error", new ActionMessage("username.exists"));

			saveErrors(request, errors);

			return mapping.findForward("signup");

		}

	}

}
